const express = require('express');
const router = express.Router();
const orderController = require('../controllers/orderController');
const { authenticate } = require('../middleware/authMiddleware');
const models = require('../models');

// 添加路由日志中间件
router.use((req, res, next) => {
  next();
});

// 获取订单详情
router.get('/detail', authenticate, orderController.getOrderDetail);

// 通过预约ID查询订单
router.get('/reservation/:reservationId', authenticate, async (req, res) => {
  try {
    const { reservationId } = req.params;
    const userId = req.user?.id;

    if (!reservationId) {
      return res.status(400).json({
        code: 400,
        message: '缺少必要参数',
        data: null
      });
    }

    // 查询与预约ID关联的订单
    let order = null;
    try {
      if (models.Order) {
        order = await models.Order.findOne({
          where: { 
            reservation_id: reservationId
          }
        });
      }
    } catch (error) {
      console.error('查询关联订单失败:', error);
    }

    if (!order) {
      return res.status(404).json({
        code: 404,
        message: '关联订单不存在',
        data: null
      });
    }

    // 返回订单详情
    return res.status(200).json({
      code: 200,
      message: '获取订单详情成功',
      data: {
        id: order.id,
        order_no: order.order_no,
        amount: order.amount,
        status: order.status,
        create_time: order.create_time,
        payment_time: order.payment_time,
        payment_method: order.payment_method,
        remark: order.remark,
        orderType: order.order_type,
        reservation_id: order.reservation_id
      }
    });
  } catch (error) {
    console.error('获取关联订单详情失败:', error);
    return res.status(500).json({
      code: 500,
      message: '获取订单详情失败，请稍后重试',
      data: null
    });
  }
});

// 获取用户订单列表
router.get('/list', authenticate, orderController.getUserOrders);

// 取消订单
router.post('/cancel/:id', authenticate, orderController.cancelOrder);

module.exports = router; 